package com.rajaev.dtu.tractor.domain.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.client.MongoCursor;
import com.rajaev.dtu.tractor.app.scheduleTask.BatteryInspectScheduleTask;
import com.rajaev.dtu.tractor.app.service.BatteryInspectService;
import com.rajaev.dtu.tractor.domain.entity.*;
import com.rajaev.dtu.tractor.domain.repository.mysql.BatteryDao;
import com.rajaev.dtu.tractor.domain.repository.mysql.BatteryInspectDao;
import com.rajaev.dtu.tractor.domain.repository.mysql.UserDao;
import com.rajaev.dtu.tractor.infrastructure.base.common.Constants;
import com.rajaev.dtu.tractor.infrastructure.base.enums.BatterInspectTaskState;
import com.rajaev.dtu.tractor.infrastructure.base.vo.BatteryInspectVo;
import com.rajaev.dtu.tractor.infrastructure.helper.MongoDbUtils;
import com.rajaev.dtu.tractor.infrastructure.helper.UserSecurityUtil;
import com.rajaev.dtu.tractor.infrastructure.security.UserContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Sorts.*;

/**
 * @Created with IDEA
 * @author: tianjie
 * @Date:2019/4/11
 * @Time:10:17
 */
@Service
public class BatteryInspectServiceImpl implements BatteryInspectService {

    @Autowired
    BatteryDao batteryDao;

    @Autowired
    BatteryInspectDao batteryInspectDao;

    @Autowired
    UserDao userDao;

    @Autowired
    MongoDbUtils mongoDbUtils;

    @Autowired
    BatteryInspectScheduleTask batteryInspectScheduleTask;

    @Autowired
    UserSecurityUtil userSecurityUtil;


    private static Integer default_page_size = 10;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitAInspectTask(Integer userId) {

        //查询总的车辆
        int all = batteryDao.countAllByCuLoginUserId(userId);

        //生成一个巡检任务
        BatteryInspectTaskPo batteryInspectTaskPo = new BatteryInspectTaskPo();
        batteryInspectTaskPo.setBatteryCount(all);
        batteryInspectTaskPo.setCreateUserId(userId);
        batteryInspectDao.insert(batteryInspectTaskPo);

        //生成巡检任务的子任务，插入mongodb数据库中
        //先删除残留的数据
        mongoDbUtils.getDatabase()
                .getCollection(Constants.batteryInspectTaskCollectionName)
                .deleteMany(eq("taskId", batteryInspectTaskPo.getTaskId()));

        for (int i = 0; i < all; i = i + default_page_size) {
            List<BatteryPo> list = batteryDao.selectBattery(i, default_page_size,userId);
            List<Document> documents = new ArrayList<>();
            list.forEach(batteryPo -> {
                Document document = new Document();
                document.put("taskId", batteryInspectTaskPo.getTaskId());
                document.put("vin", batteryPo.getVin());
                document.put("state", BatterInspectTaskState.NO_COMPLETE.getCode());
                documents.add(document);
            });
            mongoDbUtils.getDatabase().getCollection(Constants.batteryInspectTaskCollectionName).insertMany(documents);
        }

        //发起一次检查
        batteryInspectScheduleTask.doInspect();
    }

    @Override
    public List<BatteryInspectTaskPo> selectNoCompleteTask() {
        return batteryInspectDao.selectNoComplete();
    }


    @Override
    public PageInfo<BatteryInspectVo> pageQueryInspectVo(HttpServletRequest request, Integer pageSize, Integer pageNum) {
        //获取当前登录用户的id
        UserInfo userInfo = userSecurityUtil.getLoginUser(request).getUserInfo();

        PageInfo<BatteryInspectVo> pageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> batteryInspectDao.selectAllTasks(userInfo.getId()));
        pageInfo.getList().forEach(batteryInspectVo -> {
            int taskId = batteryInspectVo.getId();
            long completeCount = mongoDbUtils.getDatabase().getCollection(Constants.batteryInspectTaskCollectionName).countDocuments(and(eq("taskId", taskId), eq("state", 1)));
            batteryInspectVo.setComplete(completeCount);
        });
        return pageInfo;
    }


    @Override
    public PageInfo<BatteryInspectTaskDetail> pageQueryInspectDetail(Integer pageSize, Integer pageNum, Integer taskId, String keyword, String orderField, Integer order) {
        if (StringUtils.isEmpty(orderField)) {
            orderField = "totalScore";
            order = 1;
        }
        MongoCursor<Document> mongoCursor = mongoDbUtils.getDatabase().getCollection(Constants.batteryInspectTaskCollectionName)
                .find(and(eq("taskId", taskId), eq("state", 1)))
                .sort(orderBy(order == 1 ? ascending(orderField) : descending(orderField)))
                .skip(pageSize * (pageNum - 1))
                .limit(pageSize)
                .iterator();
        long total = mongoDbUtils.getDatabase().getCollection(Constants.batteryInspectTaskCollectionName).countDocuments(and(eq("taskId", taskId), eq("state", 1)));
        List<BatteryInspectTaskDetail> list = new ArrayList<>();
        while (mongoCursor.hasNext()) {
            Document document = mongoCursor.next();
            BatteryInspectTaskDetail batteryInspectTaskDetail = new BatteryInspectTaskDetail();
            batteryInspectTaskDetail.setSoc(document.getString("soc"));
            batteryInspectTaskDetail.setVin(document.getString("vin"));
            batteryInspectTaskDetail.setBz(document.getString("bz"));
            batteryInspectTaskDetail.setMaxSingleV(document.getString("maxSingleV"));
            batteryInspectTaskDetail.setSubT(document.getInteger("subT",0));
            batteryInspectTaskDetail.setSubV(document.getInteger("subV",0));
            batteryInspectTaskDetail.setPlateNo(document.getString("plateNo"));
            batteryInspectTaskDetail.setMaxFaultLevel(document.getInteger("maxFaultLevel",0));
            batteryInspectTaskDetail.setMaxTStr(document.getString("maxTStr"));
            batteryInspectTaskDetail.setMinTStr(document.getString("minTStr") == null ? null : document.getString("minTStr"));
            batteryInspectTaskDetail.setSystemFaultLevel(document.getInteger("systemFaultLevel",0));
            list.add(batteryInspectTaskDetail);
        }
        PageInfo<BatteryInspectTaskDetail> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(total);
        pageInfo.setPageSize(pageSize);
        pageInfo.setNextPage(pageSize * (pageNum + 1) <= total?pageNum+1:pageNum);
        pageInfo.setPrePage(pageNum>1?pageNum-1:pageNum);
        pageInfo.setPageNum(pageNum);
        pageInfo.setHasNextPage(pageSize * (pageNum + 1) <= total);
        return pageInfo;
    }
}
